package com.roncoo.education.util.dingd;


import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.*;
import com.dingtalk.api.response.*;
import com.taobao.api.ApiException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;


/**
 * 钉钉配置
 */
@Slf4j
@Component()
public class DingDUtil {

    @Autowired
    private DingDingProperties properties;

//    private String accessToken;

//    @PostConstruct
//    public void initMethod(){
//
//    }

//    public final static String APP_KEY="dinga8ffctrcspoameuh";
//
//    public final static String APP_SECRET="nKXzCjO2xD5P6VOfnQQvQwwk1iPDU-C1T_zUIb7SKaVtMSb-apBCDXu127dHrav_";
//
//    public final static Long AGENT_ID = 636304698L;

    /**
        获取access_token
     */
    public final static String GET_ACCESS_TOKEN_URL="https://oapi.dingtalk.com/gettoken";

    /**
     *  免登陆URL
     */
    public final static String NO_PASSWORD_LOGIN_URL="https://oapi.dingtalk.com/user/getuserinfo";

    /**
     * 获取钉钉用户信息
     */
    public final static String GET_USER_INFO_URL="https://oapi.dingtalk.com/user/get";
    /**
     * 获取部门列表
     */
    public final static String GET_DEPARTMENT_LIST_URL="https://oapi.dingtalk.com/department/list";

    /**
     * 发送工作通知消息
     */
    public final static String SEND_MESSAGE_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2";

    /**
     * 查询工作通知消息的发送结果
     */
    public final static String SEND_MESSAGE_RESULT_URL = "https://oapi.dingtalk.com/topapi/message/corpconversation/getsendresult";
    /**
     * 获取部门人员
     */
    public final static String GET_USERINFO = "https://oapi.dingtalk.com/user/simplelist";

    public String getAccessToken(){
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(GET_ACCESS_TOKEN_URL);
            OapiGettokenRequest request = new OapiGettokenRequest();
            request.setAppkey(properties.getAppKey());
            request.setAppsecret(properties.getAppSecret());
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            return response.getAccessToken();
        }catch (Exception e){

        }
        return null;
    }

    public  String getUserId(String code,String accessToken){
        try {
            DingTalkClient client = new DefaultDingTalkClient(NO_PASSWORD_LOGIN_URL);
            OapiUserGetuserinfoRequest request = new OapiUserGetuserinfoRequest();
            request.setCode(code);
            request.setHttpMethod("GET");
            OapiUserGetuserinfoResponse response = client.execute(request, accessToken);
            return response.getUserid();
        }catch (Exception e){

        }
        return "";

    }

    public OapiUserGetResponse getUserInfo(String userId,String accessToken){
        try {
            DingTalkClient client = new DefaultDingTalkClient(GET_USER_INFO_URL);
            OapiUserGetRequest request = new OapiUserGetRequest();
//            request.setUserid("zhangsan");
            request.setUserid(userId);
            request.setHttpMethod("GET");
            return client.execute(request, accessToken);
        }catch (Exception e){

        }
        return null;

    }



    /**
     * 获取部门列表
     * @param accessToken
     * @return
     * @throws ApiException 
     */
    public OapiDepartmentListResponse getDepartments(String accessToken){
    	try {
			DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
			OapiDepartmentListRequest req = new OapiDepartmentListRequest();
			req.setHttpMethod("GET");
			OapiDepartmentListResponse rsp = client.execute(req, accessToken);
			System.out.println(rsp.getBody());
			return rsp;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
    }

    /**
     * 发送工作通知消息
     * @param dingUserId 钉钉用户id
     * @param accessToken token
     * @param message 消息
     * @return OapiMessageCorpconversationAsyncsendV2Response
     * @author wangrong
     */
    public OapiMessageCorpconversationAsyncsendV2Response sendMessage(String dingUserId, String message,String accessToken) {
        DingTalkClient client = new DefaultDingTalkClient(SEND_MESSAGE_URL);

        OapiMessageCorpconversationAsyncsendV2Request request = new OapiMessageCorpconversationAsyncsendV2Request();
        request.setUseridList(dingUserId);
        request.setAgentId(Long.parseLong(properties.getAgentId()));
        request.setToAllUser(false);

        //text类型消息
        OapiMessageCorpconversationAsyncsendV2Request.Msg msg = new OapiMessageCorpconversationAsyncsendV2Request.Msg();
        msg.setMsgtype("text");
        msg.setText(new OapiMessageCorpconversationAsyncsendV2Request.Text());
        msg.getText().setContent(message);
        request.setMsg(msg);

        try {
            return client.execute(request,accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询工作通知消息的发送结果
     * @param taskId 异步任务的id
     * @param accessToken token
     * @return OapiMessageCorpconversationGetsendresultResponse
     * @author wangrong
     */
    public OapiMessageCorpconversationGetsendresultResponse getSendResult(Long taskId,String accessToken) {
        DingTalkClient client = new DefaultDingTalkClient(SEND_MESSAGE_RESULT_URL);
        OapiMessageCorpconversationGetsendresultRequest request  = new OapiMessageCorpconversationGetsendresultRequest();
        request.setAgentId(Long.parseLong(properties.getAgentId()));
        request.setTaskId(taskId);
        try {
            return client.execute(request, accessToken);
        } catch (ApiException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 获取部门人员信息
     * @param accessToken
     * @param department
     * @return
     * @throws ApiException 
     */
    public OapiUserSimplelistResponse getUserInfo(String accessToken,Long department) throws ApiException{
    	DingTalkClient client = new DefaultDingTalkClient(GET_USERINFO);
    	OapiUserSimplelistRequest request = new OapiUserSimplelistRequest();
    	request.setDepartmentId(department);
    	request.setOffset(0L);
    	request.setSize(10L);
    	request.setHttpMethod("GET");
        return client.execute(request, accessToken);
    }
    
    public OapiUserGetResponse getuser(String accessToken,String realName) {
    	try {
			DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/user/get");
			OapiUserGetRequest req = new OapiUserGetRequest();
			req.setUserid(realName);
			req.setHttpMethod("GET");
			OapiUserGetResponse rsp = client.execute(req, accessToken);
			System.out.println(rsp.getBody());
			return rsp;
		} catch (ApiException e) {
			e.printStackTrace();
		}
		return null;
	}
//    public static void main(String[] args) {
//        try {
//            DefaultDingTalkClient client = new DefaultDingTalkClient(GET_ACCESS_TOKEN_URL);
//            OapiGettokenRequest request = new OapiGettokenRequest();
//            request.setAppkey("dinga8ffctrcspoameuh");
//            request.setAppsecret("nKXzCjO2xD5P6VOfnQQvQwwk1iPDU-C1T_zUIb7SKaVtMSb-apBCDXu127dHrav_");
//            request.setHttpMethod("GET");
//            OapiGettokenResponse response = client.execute(request);
//            System.out.println(response.getAccessToken());
//        }catch (Exception e){
//
//        }
//        try{
//            DingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/department/list");
//            OapiDepartmentListRequest request = new OapiDepartmentListRequest();
//            request.setHttpMethod("GET");
//            OapiDepartmentListResponse response = client.execute(request,"d494a8eb6f203cdc8e15dcd8389e83cf" );
//            List<OapiDepartmentListResponse.Department> list=response.getDepartment();
//            System.out.println(list.get(0).getId()+list.get(0).getName());
//        }catch (Exception e){
//            e.printStackTrace();
//        }



//    }

}
